var rtcroom = require('../../../utils/rtcroom.js');
var util = require('../../../utils/util.js')
var app  = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
      roomID: '',         // 房间id
      roomname: '',       // 房间名称
      beauty: 5,
      muted: false,
      debug: false,
      frontCamera: true,
      assistant:{},
      startTime:null,
      endTime:null,
      flagStatus:1,
      selToID:null,
      dynatownId:null,
      hideBg:false,
      flag:false,
      status:"正在呼叫对方"
    },
    onRoomEvent: function (e) {
      var self = this;
      console.log('收到消息:', e);
      switch (e.detail.tag) {
        case 'recvTextMsg': {
          var obj=JSON.parse(e.detail.detail);
          console.log('收到消息recvTextMsg:', e.detail.detail,obj.textMsg);
          if(obj.textMsg.indexOf(self.data.selToID+"离开房间")>0){
            wx.showToast({
              title: '视频中断',
              icon: 'none',
              duration: 1500,
            })
            self.setData({
              flagStatus: 3, // 视频结束
              hideBg: false,
              endTime:Date.now()
            });
            // self.updateDynatown("0"); //修改置业顾问当前忙碌状态 videoTime
            if(self.data.flag){
              if(self.data.startTime && self.data.endTime){
                var st = Math.floor((self.data.endTime - self.data.startTime)/1000);
                var mini=Math.floor(st/60);
                var second=st%60;
                var videoTime = (mini>9?mini:("0"+mini)) +":"+(second>9?second:("0"+second))
                console.log(mini,second,videoTime);
                wx.redirectTo({
                  url:'../../chat/chat?videoStatus=1&videoTime='+videoTime
                })
              }
              else{
                wx.redirectTo({
                  url:'../../chat/chat?videoStatus=2'
                })
              }
              
            }
            else{
              // console.log('onRoomEvent')
              wx.navigateBack({ delta: 1 });
            }
          }
          if(obj.textMsg.indexOf(self.data.selToID+"进入房间")>0){
            self.setData({
              flagStatus: 2,
              startTime: Date.now()
            });
            console.log("***接通***",self.data.hideBg)
            // startTime=Date.now()
          }
          if(obj.textMsg.indexOf("108")>0){
            try{
              var obt=JSON.parse(obj.textMsg);
              console.log("==========",obt)
              if(obt.type==="108"||obt.type===108){
                self.setData({
                  hideBg: true,
                });
                console.log("***对方接通视频***",self.data.hideBg)
              }
            }catch(e){

            }
            
          }
          if(obj.textMsg.indexOf("109")>0){
            try{
              var obt=JSON.parse(obj.textMsg);
               console.log("==========",obt)
              if(obt.type==="109"||obt.type===109){
                self.setData({
                  hideBg: false,
                });
                console.log("***对方隐藏视频***",self.data.hideBg)
              }
            }catch(e){

            }
            
            // startTime=Date.now()
          }
          break;
        }
        case 'roomClosed': {
          /*
            房间关闭时会收到此通知，客户可以提示用户房间已经关闭，做清理操作
          */
          // 在房间内部才显示提示
          console.log("roomClose:", e.detail.detail);
          this.setData({
              flagStatus: 3,
              endTime: Date.now()
          });
          // self.updateDynatown("0"); //修改置业顾问当前忙碌状态
          var pages = getCurrentPages();
          console.log(pages, pages.length, pages[pages.length - 1].__route__);
          if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/multiroom/room/room')) {
            wx.showModal({
              title: '提示',
              content: e.detail.detail || '房间已解散',
              showCancel: false,
              complete: function () {
              pages = getCurrentPages();
                console.log(pages, pages.length, pages[pages.length - 1].__route__);
                if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/multiroom/room/room')) {
                  // wx.navigateBack({ delta: 1 });
                  if(self.data.flag){
                    if(self.data.endTime&&self.data.startTime){
                      var st = Math.floor((self.data.endTime - self.data.startTime)/1000);
                      var mini=Math.floor(st/60);
                      var second=st%60;
                      var videoTime = (mini>9?mini:("0"+mini)) +":"+(second>9?second:("0"+second))
                      console.log(mini,second,videoTime);
                      wx.redirectTo({
                        url:'../../chat/chat?videoStatus=1&videoTime='+videoTime
                      })
                    }
                    else{
                      wx.redirectTo({
                        url:'../../chat/chat?videoStatus=2'
                      })
                    }
                  }
                  else{
                    // console.log('roomClosed')
                    wx.navigateBack({ delta: 1 });
                  }
                }
              }
            });
          }
          break;
        }
        case 'error': {
          // 在房间内部才显示提示
          // var rtcroomCom = this.selectComponent('#rtcroom');
          console.error("error:", e.detail.detail);
          // console.log("error:", e.detail.detail);
          // if(e.detail.detail.indexOf("未获取到录音功能权限")>=0){
          //   console.log("***error***",e.detail.detail)
          //   rtcroomCom.exitRoom()
          //   wx.navigateBack({ delta: 1 });
          // }
          // if(e.detail.detail.indexOf("未获取到摄像头功能权限")>=0){
          //   console.log("***error***",e.detail.detail)
          //   rtcroomCom.exitRoom()
          //   wx.navigateBack({ delta: 1 });
          // }
          var pages = getCurrentPages();
          console.log(pages, pages.length, pages[pages.length - 1].__route__);
          if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/multiroom/room/room')) {
            wx.showModal({
              title: '提示',
              content: e.detail.detail,
              showCancel: false,
              complete: function () {
                pages = getCurrentPages();
                if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/multiroom/room/room')) {
                  if(self.data.flag){
                    if(self.data.endTime&&self.data.startTime){
                      var st = Math.floor((self.data.endTime - self.data.startTime)/1000);
                      var mini=Math.floor(st/60);
                      var second=st%60;
                      var videoTime = (mini>9?mini:("0"+mini)) +":"+(second>9?second:("0"+second))
                      console.log(mini,second,videoTime);
                      wx.redirectTo({
                        url:'../../chat/chat?videoStatus=1&videoTime='+videoTime
                      })
                    }
                    else{
                      wx.redirectTo({
                        url:'../../chat/chat?videoStatus=2'
                      })
                    }
                  }
                  else{
                    // console.log('error')
                    wx.navigateBack({ delta: 1 });
                  }
                }
              }
            });
          }
          break;
        }
      }
    },
    sendComment: function() {
      var rtcroomCom = this.selectComponent('#rtcroom');
      if (rtcroomCom) {
          //发送消息
          let accountInfo = rtcroom.getAccountInfo();
          // console.log(accountInfo)
          let parm = {
            consultantName : accountInfo.opt.username,
            currentTime : Date.now(),
            roomNum : this.data.roomID,
            customerId : accountInfo.userSplitID,
            customerGender: accountInfo.gender,
            customerLoginId:accountInfo.loginid,
            customerMobile: app.globalData.phone || "",
            customerNickname : accountInfo.userName,
            customerAvatar : accountInfo.userAvatar,
          }
          let data = {
            "csyzwfelab20180425hhhdfq":"secretkey",
            "param":parm,
            "type":512,
            "typedesc":"调起视频"
          };
          
          console.log("*****sendComment*****",JSON.stringify(data))
          // rtcroomCom.sendTextMsg("123456zjs");
          let tp={
            flag:"1", // 发送视频邀请消息
            myselToID:accountInfo.selToID
          }
          rtcroomCom.sendTextMsg(JSON.stringify(data),tp);
      }
    },
    decline:function(){
      var self = this;
      console.log("***decline***",self.data.flag);
      var rtcroomCom = this.selectComponent('#rtcroom');
      let roomInfo = rtcroom.getRoomInfo();
      console.log("***roomInfo***",roomInfo.isPush)
      if(!roomInfo.isPush){
        return false;
      }
      if(self.data.flag){
        if(self.data.endTime&&self.data.startTime){
          var st = Math.floor((self.data.endTime - self.data.startTime)/1000);
          var mini=Math.floor(st/60);
          var second=st%60;
          var videoTime = (mini>9?mini:("0"+mini)) +":"+(second>9?second:("0"+second))
          console.log(mini,second,videoTime);
          wx.redirectTo({
            url:'../../chat/chat?videoStatus=1&videoTime='+videoTime
          })
        }
        else{
          wx.redirectTo({
            url:'../../chat/chat?videoStatus=2'
          })
        }
        
      }
      else{
        wx.navigateBack({ delta: 1 });
      }
    },
    changeCamera: function () {
      // this.sendComment()
      // var rtcroomCom = this.selectComponent('#rtcroom');
      // if (rtcroomCom) {
      //   rtcroomCom.switchCamera();
      // }
      // this.setData({
      //   frontCamera: !this.data.frontCamera
      // })
    },
    setBeauty: function () {
      var rtcroomCom = this.selectComponent('#rtcroom');
      if (rtcroomCom) {
        let accountInfo = rtcroom.getAccountInfo();
        let data = {
          "type":106,
          "time":Date.now(),
          "param":{
            "text":"123456zjs",
          }
        }
        let parm={
          flag:"0" // 发送普通文字消息
        }
        rtcroomCom.sendTextMsg(JSON.stringify(data),parm);
        rtcroom.getRoomList({
          data:{
            index: 0,
            cnt: 20
          },
          success: function(ret) {
            console.log(ret)
            // self.setData({
            //   roomList: ret.rooms
            // });
            // console.log(this.roomList);
            console.log('拉取房间列表成功',ret);
            // callback && callback();
          },
          fail: function(ret) {
            console.log(ret);
            wx.showModal({
              title: '提示',
              content: ret.errMsg,
              showCancel: false
            });
            // callback && callback();
          }
        });
      }
      // this.data.beauty = (this.data.beauty == 0 ? 5 : 0);
      // this.setData({
      //   beauty: this.data.beauty
      // });
    },
    changeMute: function () {
      this.data.muted = !this.data.muted;
      this.setData({
        muted: this.data.muted
      });
    },
    showLog: function () {
      this.data.debug = !this.data.debug;
      this.setData({
        debug: this.data.debug
      });
    },
    updateDynatown:function(status){//修改置业顾问状态 1忙碌  0空闲
        var that = this;
        var status = status;
        var advisterId = that.data.dynatownId;
        var houseid = app.globalData.houseid;
        console.log("***updateDynatown***",status,advisterId)
        wx.request({
            url: util.url(),
            method:'POST',
            data: util.reformParam(util.updateDynatown,{status: status,advisterId:advisterId,houseid:houseid}),
            success:function(res){
              console.log("***updateDynatown_res***",res)
            },
            fail:function(re){

            }
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      console.log("********------",options)
      if(options && options.isSuc){
        this.setData({
          flag:true
        });
      }
      else{
        this.setData({
          flag:false
        });
      }
      var self = this;
      wx.getSetting({
          success: (response) => {
            console.log("=======rtcroomCom.onLoad***getSetting",response)
            // 没有授权
            if (!response.authSetting['scope.record'] || !response.authSetting['scope.camera']){
              wx.openSetting({
                success: (res) => {
                    if(res.authSetting['scope.record'] && res.authSetting['scope.camera']){
                      self.init(options)
                    }
                    else{
                      console.log("******openSetting——success-other&&&&&&&",res)
                      if(self.data.flag){
                        wx.redirectTo({
                          url:'../../chat/chat'
                        })
                      }
                      else{
                        wx.navigateBack({ delta: 1 });
                      }
                    }
                },
                fail:(res)=>{
                  console.log("******openSetting错误&&&&&&&",res)
                  wx.showModal({
                    title: '提示',
                    content: '操作太快,请稍后再试',
                    success: function(res) {
                      if (res.confirm) {
                        if(self.data.flag){
                          wx.redirectTo({
                            url:'../../chat/chat'
                          })
                        }
                        else{
                          wx.navigateBack({ delta: 1 });
                        }
                      } else if (res.cancel) {
                        if(self.data.flag){
                          wx.redirectTo({
                            url:'../../chat/chat'
                          })
                        }
                        else{
                          wx.navigateBack({ delta: 1 });
                        }
                      }
                    }
                  })
                  
                }

              })
            }
            else{
              self.init(options)
            }
          },
          fail: function () {
            // typeof cb == "function" && cb()
            wx.showToast({
              title: '系统提示:网络错误',
              icon: 'warn',
              duration: 1500,
            })
          }
      })
      // var aideData = app.globalData.aideData;
      // this.setData({
      //   aideData: aideData
      // });
      
    },
    callConsultant:function (options){

    },
    // 页面初始化
    init:function(options){
      var self =this;
      console.log('room.js onLoad');
      var time = new Date();
      time = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
      console.log('*************开始视频看房：' + time + '**************');
      console.log(options)
      self.data.role = options.type;
      self.data.roomID = options.roomID || '';
      self.data.roomname = options.roomName;
      self.data.username = options.userName;
      // self.data.consultantName = options.consultantName;
      self.setData({
        roomID: self.data.roomID,
        roomname: self.data.roomname,
        username: self.data.username
      }, function() {
        var rtcroomCom = self.selectComponent('#rtcroom');
        if (rtcroomCom) {

          console.log("rtcroomCom")
          let accountInfo = rtcroom.getAccountInfo();
          console.log(accountInfo.opt)
          self.setData({
            assistant:accountInfo.opt,
            dynatownId:accountInfo.opt.id,
            selToID:accountInfo.selToID
          })
          rtcroomCom.start(function(roomID){
            self.setData({
              roomID:roomID,
            })
            self.updateDynatown("1");
          });
        }
      });
    },
    chuli:function(){

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
      // var self = this;
      // if (!self.data.username) {
      //   wx.showModal({
      //     title: '提示',
      //     content: '登录信息还未获取到，请稍后再试',
      //     showCancel: false,
      //     complete: function () {
      //       var pages = getCurrentPages();
      //       console.log(pages, pages.length, pages[pages.length - 1].__route__);
      //       if (pages.length > 1 && (pages[pages.length - 1].__route__ == 'pages/multiroom/room/room')) {
      //         wx.navigateBack({ delta: 1 });
      //       }
      //     }
      //   });
      //   return;
      // }
      // // 设置房间标题
      // wx.setNavigationBarTitle({ title: self.data.roomname });

      //打印userID
      // var time = new Date();
      // var h = time.getHours()+'', m = time.getMinutes()+'', s = time.getSeconds()+'';
      // h.length == 1 ? (h='0'+h) : '';
      // m.length == 1 ? (m='0'+m) : '';
      // s.length == 1 ? (s='0'+s) : '';
      // time = h + ':' + m + ':' + s;

      // var rtcroomCom = this.selectComponent('#rtcroom');
      // var accountInfo = {};
      // if (rtcroomCom) {
      //   accountInfo = rtcroom.getAccountInfo();
      //   console.log(accountInfo)
      // }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      var self = this;
      console.log('room.js onShow');
      // 保持屏幕常亮
      wx.setKeepScreenOn({
        keepScreenOn: true
      })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
      var self = this;
      console.log('room.js onHide');
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      console.log('***onUnload***room.js onUnload',this.data.flagStatus);
      // this.setData({
      //   flagStatus: 3,
      //   endTime:Date.now()
      // });
      if(this.data.flagStatus==1) // 未接通
      {
        console.log("=====this.data.flagStatus======",this.data.flagStatus)
        this.updateDynatown("0"); //修改置业顾问当前空闲状态
      }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        
    },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage: function () {
    //   return {
    //     // title: '多人音视频',
    //     // path: '/pages/multiroom/roomlist/roomlist',
    //     path: '/pages/main/main',
    //     imageUrl: 'https://mc.qcloudimg.com/static/img/dacf9205fe088ec2fef6f0b781c92510/share.png'
    //   }
    // }
})